package com.schoolhelper.task.controller;

import com.schoolhelper.task.domain.TaskOrder;
import com.schoolhelper.task.service.TaskOrderService;
import com.schoolhelper.utils.JwtUtils;
import com.schoolhelper.config.FileUploadConfig;
import com.schoolhelper.notification.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务订单控制器
 * 提供任务订单相关的REST API接口
 */
@RestController
@RequestMapping("/api/task-orders")
@CrossOrigin(origins = "*")
public class TaskOrderController {
    
    @Autowired
    private TaskOrderService taskOrderService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private FileUploadConfig fileUploadConfig;
    
    @Autowired
    private NotificationService notificationService;
    
    /**
     * 从JWT token中获取当前用户ID
     * @return 用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            return jwtUtils.getUserIdFromToken(token);
        }
        throw new RuntimeException("未找到有效的用户认证信息");
    }
    
    /**
     * 处理任务列表中的头像URL
     * @param taskOrders 任务列表
     */
    private void processAvatarUrls(List<TaskOrder> taskOrders) {
        for (TaskOrder taskOrder : taskOrders) {
            // 处理发布者头像
            if (taskOrder.getPublisherAvatar() != null && !taskOrder.getPublisherAvatar().isEmpty() && !taskOrder.getPublisherAvatar().startsWith("http")) {
                taskOrder.setPublisherAvatar(fileUploadConfig.getFileUrl(taskOrder.getPublisherAvatar()));
            }
            
            // 处理接单者头像
            if (taskOrder.getAccepterAvatar() != null && !taskOrder.getAccepterAvatar().isEmpty() && !taskOrder.getAccepterAvatar().startsWith("http")) {
                taskOrder.setAccepterAvatar(fileUploadConfig.getFileUrl(taskOrder.getAccepterAvatar()));
            }
        }
    }
    
    /**
     * 创建新的任务订单
     * @param taskOrder 任务订单对象
     * @return 创建结果
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createTaskOrder(@RequestBody TaskOrder taskOrder) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 基本参数验证
            if (taskOrder.getTitle() == null || taskOrder.getTitle().trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "任务标题不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            if (taskOrder.getCategory() == null || taskOrder.getCategory().trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "任务分类不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            if (taskOrder.getPrice() == null || taskOrder.getPrice().doubleValue() <= 0) {
                response.put("success", false);
                response.put("message", "任务金额必须大于0");
                return ResponseEntity.badRequest().body(response);
            }
            if (taskOrder.getRequiredTime() == null) {
                response.put("success", false);
                response.put("message", "要求完成时间不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            if (taskOrder.getPublisherId() == null) {
                response.put("success", false);
                response.put("message", "发布者ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            TaskOrder createdOrder = taskOrderService.createTaskOrder(taskOrder);
            response.put("success", true);
            response.put("message", "任务订单创建成功");
            response.put("data", createdOrder);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "创建任务订单失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 根据ID获取任务订单详情
     * @param id 订单ID
     * @return 任务订单详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getTaskOrderById(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            TaskOrder taskOrder = taskOrderService.getTaskOrderById(id);
            response.put("success", true);
            response.put("data", taskOrder);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }
    
    /**
     * 获取所有任务订单列表
     * @return 任务订单列表
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllTaskOrders() {
        Map<String, Object> response = new HashMap<>();
        try {
            List<TaskOrder> taskOrders = taskOrderService.getAllTaskOrders();
            
            // 处理头像URL
            processAvatarUrls(taskOrders);
            
            response.put("success", true);
            response.put("data", taskOrders);
            response.put("total", taskOrders.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取任务订单列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 根据状态获取任务订单列表
     * @param status 订单状态
     * @return 任务订单列表
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<Map<String, Object>> getTaskOrdersByStatus(@PathVariable String status) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<TaskOrder> taskOrders = taskOrderService.getTaskOrdersByStatus(status);
            
            // 处理头像URL
            processAvatarUrls(taskOrders);
            
            response.put("success", true);
            response.put("data", taskOrders);
            response.put("total", taskOrders.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
    
    /**
     * 获取用户发布的任务订单列表
     * @param publisherId 发布者用户ID
     * @return 任务订单列表
     */
    @GetMapping("/publisher/{publisherId}")
    public ResponseEntity<Map<String, Object>> getMyPublishedOrders(@PathVariable Long publisherId) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<TaskOrder> taskOrders = taskOrderService.getMyPublishedOrders(publisherId);
            
            // 处理头像URL
            processAvatarUrls(taskOrders);
            
            response.put("success", true);
            response.put("data", taskOrders);
            response.put("total", taskOrders.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
    
    /**
     * 获取用户接受的任务订单列表
     * @param accepterId 接单者用户ID
     * @return 任务订单列表
     */
    @GetMapping("/accepter/{accepterId}")
    public ResponseEntity<Map<String, Object>> getMyAcceptedOrders(@PathVariable Long accepterId) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<TaskOrder> taskOrders = taskOrderService.getMyAcceptedOrders(accepterId);
            
            // 处理头像URL
            processAvatarUrls(taskOrders);
            
            response.put("success", true);
            response.put("data", taskOrders);
            response.put("total", taskOrders.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
    
    /**
     * 根据分类获取任务订单列表
     * @param category 任务分类
     * @return 任务订单列表
     */
    @GetMapping("/category/{category}")
    public ResponseEntity<Map<String, Object>> getTaskOrdersByCategory(@PathVariable String category) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<TaskOrder> taskOrders = taskOrderService.getTaskOrdersByCategory(category);
            
            // 处理头像URL
            processAvatarUrls(taskOrders);
            
            response.put("success", true);
            response.put("data", taskOrders);
            response.put("total", taskOrders.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
    
    /**
     * 接受任务订单
     * @param orderId 订单ID
     * @param requestBody 请求体，包含接单者ID
     * @return 接单结果
     */
    @PostMapping("/{orderId}/accept")
    public ResponseEntity<Map<String, Object>> acceptTaskOrder(@PathVariable Long orderId, @RequestBody Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 添加调试日志
            System.out.println("接单请求 - 订单ID: " + orderId);
            System.out.println("请求体: " + requestBody);
            
            // 参数验证
            if (requestBody.get("accepterId") == null) {
                response.put("success", false);
                response.put("message", "接单者ID不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }
            
            Long accepterId = Long.valueOf(requestBody.get("accepterId").toString());
            System.out.println("接单者ID: " + accepterId);
            
            boolean success = taskOrderService.acceptTaskOrder(orderId, accepterId);
            if (success) {
                // 获取任务信息以创建通知
                try {
                    TaskOrder taskOrder = taskOrderService.getTaskOrderById(orderId);
                    if (taskOrder != null) {
                        // 创建通知给发布者
                        String title = "您的任务已被接单";
                        String content = "您发布的任务《" + taskOrder.getTitle() + "》已被接单，请及时关注任务进度。";
                        notificationService.createTaskNotification(
                            taskOrder.getPublisherId(), 
                            "TASK_ACCEPTED", 
                            title, 
                            content, 
                            orderId, 
                            accepterId
                        );
                    }
                } catch (Exception e) {
                    // 通知创建失败不影响接单操作
                    System.err.println("创建接单通知失败: " + e.getMessage());
                }
                
                response.put("success", true);
                response.put("message", "接单成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "接单失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (IllegalArgumentException e) {
            System.err.println("参数错误: " + e.getMessage());
            response.put("success", false);
            response.put("message", "参数错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (RuntimeException e) {
            System.err.println("业务逻辑错误: " + e.getMessage());
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (Exception e) {
            System.err.println("系统错误: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "系统错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 完成任务订单
     * @param orderId 订单ID
     * @return 完成结果
     */
    @PutMapping("/{orderId}/complete")
    public ResponseEntity<Map<String, Object>> completeTaskOrder(@PathVariable Long orderId, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 从JWT token中获取当前用户ID
            Long userId = getCurrentUserId(request);
            System.out.println("完成任务请求 - orderId: " + orderId + ", userId: " + userId);
            
            boolean success = taskOrderService.completeTaskOrder(orderId, userId);
            if (success) {
                System.out.println("任务完成成功，开始创建通知");
                // 获取任务信息以创建通知
                try {
                    TaskOrder taskOrder = taskOrderService.getTaskOrderById(orderId);
                    if (taskOrder != null) {
                        System.out.println("获取任务信息成功 - taskId: " + taskOrder.getId() + 
                                         ", publisherId: " + taskOrder.getPublisherId() + 
                                         ", title: " + taskOrder.getTitle());
                        
                        // 创建通知给发布者
                        String title = "您的任务已完成";
                        String content = "您发布的任务《" + taskOrder.getTitle() + "》已完成，请确认任务结果。";
                        boolean notificationResult = notificationService.createTaskNotification(
                            taskOrder.getPublisherId(), 
                            "TASK_COMPLETED", 
                            title, 
                            content, 
                            orderId, 
                            userId
                        );
                        System.out.println("通知创建结果: " + notificationResult);
                    } else {
                        System.err.println("获取任务信息失败: taskOrder为null");
                    }
                } catch (Exception e) {
                    // 通知创建失败不影响完成操作
                    System.err.println("创建完成通知失败: " + e.getMessage());
                    e.printStackTrace();
                }
                
                response.put("success", true);
                response.put("message", "任务完成");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "操作失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (Exception e) {
            System.err.println("完成任务失败: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
    
    /**
     * 取消任务订单（发布者取消）
     * @param orderId 订单ID
     * @return 取消结果
     */
    @PutMapping("/{orderId}/cancel")
    public ResponseEntity<Map<String, Object>> cancelTaskOrder(@PathVariable Long orderId, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 从JWT token中获取当前用户ID
            Long userId = getCurrentUserId(request);
            
            // 获取任务信息以创建通知
            TaskOrder taskOrder = null;
            try {
                taskOrder = taskOrderService.getTaskOrderById(orderId);
            } catch (Exception e) {
                System.err.println("获取任务信息失败: " + e.getMessage());
            }
            
            boolean success = taskOrderService.cancelTaskOrder(orderId, userId);
            if (success) {
                // 如果任务已被接单，创建通知给接单者
                if (taskOrder != null && taskOrder.getAccepterId() != null) {
                    try {
                        String title = "您接的任务已被取消";
                        String content = "您接的任务《" + taskOrder.getTitle() + "》已被发布者取消，请查看其他任务。";
                        notificationService.createTaskNotification(
                            taskOrder.getAccepterId(), 
                            "TASK_CANCELLED", 
                            title, 
                            content, 
                            orderId, 
                            userId
                        );
                    } catch (Exception e) {
                        // 通知创建失败不影响取消操作
                        System.err.println("创建取消通知失败: " + e.getMessage());
                    }
                }
                
                response.put("success", true);
                response.put("message", "任务已取消发布");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "取消失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    /**
     * 取消接单（接单者取消）
     * @param orderId 订单ID
     * @return 取消结果
     */
    @PutMapping("/{orderId}/cancel-accept")
    public ResponseEntity<Map<String, Object>> cancelAcceptTaskOrder(@PathVariable Long orderId, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 从JWT token中获取当前用户ID
            Long userId = getCurrentUserId(request);
            
            // 获取任务信息以创建通知
            TaskOrder taskOrder = null;
            try {
                taskOrder = taskOrderService.getTaskOrderById(orderId);
            } catch (Exception e) {
                System.err.println("获取任务信息失败: " + e.getMessage());
            }
            
            boolean success = taskOrderService.cancelAcceptTaskOrder(orderId, userId);
            if (success) {
                // 创建通知给发布者
                if (taskOrder != null) {
                    try {
                        String title = "您的任务被取消接单";
                        String content = "您发布的任务《" + taskOrder.getTitle() + "》的接单者已取消接单，任务重新开放。";
                        notificationService.createTaskNotification(
                            taskOrder.getPublisherId(), 
                            "TASK_CANCELLED", 
                            title, 
                            content, 
                            orderId, 
                            userId
                        );
                    } catch (Exception e) {
                        // 通知创建失败不影响取消操作
                        System.err.println("创建取消接单通知失败: " + e.getMessage());
                    }
                }
                
                response.put("success", true);
                response.put("message", "已取消接单");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "取消失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
    
    /**
     * 更新任务订单信息
     * @param orderId 订单ID
     * @param requestBody 请求体，包含任务订单信息和用户ID
     * @return 更新结果
     */
    @PutMapping("/{orderId}")
    public ResponseEntity<Map<String, Object>> updateTaskOrder(@PathVariable Long orderId, @RequestBody Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 从请求体中提取任务订单信息
            TaskOrder taskOrder = new TaskOrder();
            taskOrder.setId(orderId);
            taskOrder.setTitle((String) requestBody.get("title"));
            taskOrder.setDescription((String) requestBody.get("description"));
            taskOrder.setCategory((String) requestBody.get("category"));
            // 处理价格字段
            Object priceObj = requestBody.get("price");
            if (priceObj != null) {
                taskOrder.setPrice(new java.math.BigDecimal(priceObj.toString()));
            }
            // 处理时间字段
            Object timeObj = requestBody.get("requiredTime");
            if (timeObj != null) {
                taskOrder.setRequiredTime(java.time.LocalDateTime.parse(timeObj.toString()));
            }
            
            Long userId = Long.valueOf(requestBody.get("userId").toString());
            boolean success = taskOrderService.updateTaskOrder(taskOrder, userId);
            if (success) {
                response.put("success", true);
                response.put("message", "任务订单更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "更新失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
    
    /**
     * 删除任务订单
     * @param orderId 订单ID
     * @param userId 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/{orderId}")
    public ResponseEntity<Map<String, Object>> deleteTaskOrder(@PathVariable Long orderId, @RequestParam Long userId) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean success = taskOrderService.deleteTaskOrder(orderId, userId);
            if (success) {
                response.put("success", true);
                response.put("message", "任务订单删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "删除失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
    
    /**
     * 搜索任务订单
     * @param keyword 搜索关键词
     * @return 搜索结果
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchTaskOrders(@RequestParam(required = false) String keyword) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<TaskOrder> taskOrders = taskOrderService.searchTaskOrders(keyword);
            
            // 处理头像URL
            processAvatarUrls(taskOrders);
            
            response.put("success", true);
            response.put("data", taskOrders);
            response.put("total", taskOrders.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "搜索失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 分页获取任务订单列表
     * @param page 页码（从1开始）
     * @param size 每页大小
     * @return 分页结果
     */
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> getTaskOrdersWithPagination(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<TaskOrder> taskOrders = taskOrderService.getTaskOrdersWithPagination(page, size);
            
            // 处理头像URL
            processAvatarUrls(taskOrders);
            
            int total = taskOrderService.countTaskOrders();
            int totalPages = (int) Math.ceil((double) total / size);
            
            response.put("success", true);
            response.put("data", taskOrders);
            response.put("total", total);
            response.put("page", page);
            response.put("size", size);
            response.put("totalPages", totalPages);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取分页数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
}